#!/bin/bash

### Create pre-commit symlink if unset ###
GITDIR="";
if [ -d .git ]; then
  GITDIR=".git";
elif [ -f .git ]; then
  GITDIR=$(sed -n '/^gitdir:/{ s|.*: ||; p; }' .git);
fi
if [ ! -d "$GITDIR" ]; then
  echo "${0##*/}: error: unable to find git directory" 1>&2;
  exit 1;
fi
if [ ! -h "$GITDIR/hooks/pre-commit" ]; then
  if [ $(realpath --help 2>&1 | grep -c relative) != 0 ]; then
    HOOK=$(realpath --relative-to="$GITDIR/hooks" ./githook-pre-commit);
  else
    HOOK=$(readlink -f ./githook-pre-commit);
  fi
  ln -fs "$HOOK" "$GITDIR/hooks/pre-commit";
  echo "${0##*/}: creating git pre-commit hook symlink" 1>&2;
  exit 1;
fi

### Update version on every commit ###
if [ "$(git status --porcelain | grep -cE '^[MA].*\.lua$|^[MA].*laia-')" != 0 ]; then
  echo "${0##*/}: updating version in laia/Version.lua" 1>&2;
  sed -i 's|$Date[ :0-9-]*\$|$Date: '"$(date -u '+%Y-%m-%d %H:%M:%S')"' $|;' laia/Version.lua;
  git add laia/Version.lua;
fi

exit 0;
